package com.example.demo.io;

import java.io.*;

public class Demo02 {

    //使用随机文件流类RandomAccessFile将一个文本文件倒置输出
    public static void main(String[] args) {
        Reader reader = null;
        try {
            reader = new FileReader("E:\\client.txt");
            char cs[] = new char[200];
            int len = -1;
            while ((len = reader.read(cs)) != -1) {
                System.out.println("原文件中的内容：" + new String(cs, 0, len));
            }
            /*反转怎么做*/
            File file = new File("E:\\client.txt");
            //定义随机文件流
            RandomAccessFile raf = new RandomAccessFile(file, "r");//"r"表示只读
            StringBuffer sb = new StringBuffer();
            long length = raf.length();
            while (length > 3) {
                length--;
                //设置在那个位置发生下一个读取或写入操作
                raf.seek(length);
                int len1 = (char) raf.readByte();
                if (0 <= len1 && len1 <= 128) {
                    sb.append((char) len1 + "");
                } else {
                    length--;
                    raf.seek(--length);
                    byte[] bytes = new byte[3];
                    // bytes被复制为连续3个字节
                    raf.readFully(bytes);
                    sb.append(new String(bytes));
                }
            }
            System.out.println("翻转后的字符中的内容：" + sb.toString());
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
